package com.tjcm.tjcminspectmanager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import cn.emagsoftware.ui.ToastManager;
import cn.emagsoftware.ui.adapterview.BaseLoadAdapter;
import cn.emagsoftware.ui.adapterview.DataHolder;
import cn.emagsoftware.ui.adapterview.ViewHolder;
import cn.emagsoftware.ui.staticmanager.StaticManager;
import cn.emagsoftware.util.LogManager;
import cn.emagsoftware.util.StringUtilities;

import com.tjcm.tjcminspectmanager.manager.NetManager;
import com.tjcm.tjcminspectmanager.model.HiddenTroubleItem;
import com.tjcm.tjcminspectmanager.model.User;
import com.tjcm.tjcminspectmanager.model.User.SpecialtyType;

public class TroubleQueryActivity extends BaseActivity
{

    private LocationManager  mgr      = null;
    private LocationListener listener = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (!LoginActivity.IS_APP_RUNNING)
        {
            StaticManager.restartAppWhenDalvikRecycled(this, LoginActivity.class);
            return;
        }

        User user = (User) getIntent().getSerializableExtra("USER");

        setContentView(R.layout.troublequery);

        final Spinner type = (Spinner) findViewById(R.id.type);
        final Spinner area = (Spinner) findViewById(R.id.area);
        final EditText lon = (EditText) findViewById(R.id.lon);
        final EditText lat = (EditText) findViewById(R.id.lat);
        final Spinner level = (Spinner) findViewById(R.id.level);
        Button query = (Button) findViewById(R.id.query);
        ListView list = (ListView) findViewById(R.id.list);

        ArrayAdapter<SpecialtyType> typeAdapter = new ArrayAdapter<SpecialtyType>(this, android.R.layout.simple_spinner_item, User.SPECIALTY_TYPE);
        typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        type.setAdapter(typeAdapter);
        int index = Arrays.asList(User.SPECIALTY_TYPE).indexOf(new SpecialtyType("", user.specialtyType));
        if (index != -1)
            type.setSelection(index);
        ArrayAdapter<String> areaAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, User.AREA_NAME);
        areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        area.setAdapter(areaAdapter);
        index = Arrays.asList(User.AREA_NAME).indexOf(user.areaName);
        if (index != -1)
            area.setSelection(index);
        ArrayAdapter<String> levelAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, User.HIDDENTROUBLE_LEVEL);
        levelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        level.setAdapter(levelAdapter);
        lon.setText("0.00000");
        lat.setText("0.00000");
        mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new LocationListener()
        {
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras)
            {
                // TODO Auto-generated method stub
                lon.setText("0.00000");
                lat.setText("0.00000");
            }

            @Override
            public void onProviderEnabled(String provider)
            {
                // TODO Auto-generated method stub
                lon.setText("0.00000");
                lat.setText("0.00000");
            }

            @Override
            public void onProviderDisabled(String provider)
            {
                // TODO Auto-generated method stub
                lon.setText("0.00000");
                lat.setText("0.00000");
            }

            @Override
            public void onLocationChanged(Location location)
            {
                // TODO Auto-generated method stub
                lon.setText(location.getLongitude() + "");
                lat.setText(location.getLatitude() + "");
            }
        };
        mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, listener);
        final View foot = getLayoutInflater().inflate(R.layout.generic_loading, null);
        list.addFooterView(foot, null, false);
        final ProgressBar progress = (ProgressBar) foot.findViewById(R.id.progress);
        final TextView desc = (TextView) foot.findViewById(R.id.desc);
        final Button retry = (Button) foot.findViewById(R.id.retry);
        final BaseLoadAdapter listAdapter = new BaseLoadAdapter(this, new BaseLoadAdapter.LoadCallback()
        {
            @Override
            protected List<DataHolder> onLoad(Object arg0) throws Exception
            {
                // TODO Auto-generated method stub
                final String[] params = (String[]) arg0;
                HiddenTroubleItem[] items = NetManager.queryTroubleItems(params[0], params[1], params[2], params[3], params[4]);
                List<DataHolder> holders = new ArrayList<DataHolder>();
                for (HiddenTroubleItem item : items)
                {
                    holders.add(new DataHolder(item, 0)
                    {
                        @Override
                        public View onCreateView(Context arg0, int arg1, Object arg2)
                        {
                            // TODO Auto-generated method stub
                            View item = LayoutInflater.from(arg0).inflate(R.layout.troublelist_item, null);
                            item.setTag(new ViewHolder(item.findViewById(R.id.no), item.findViewById(R.id.text)));
                            onUpdateView(arg0, arg1, item, arg2);
                            return item;
                        }

                        @Override
                        public void onUpdateView(Context arg0, int arg1, View arg2, Object arg3)
                        {
                            // TODO Auto-generated method stub
                            View[] views = ((ViewHolder) arg2.getTag()).getParams();
                            ((TextView) views[0]).setText((arg1 + 1) + "");
                            ((TextView) views[1]).setText(StringUtilities.replaceWordsAll(params[5], "{0}", ((HiddenTroubleItem) arg3).patrolSpotId));
                        }

                        @Override
                        public void onAsyncDataExecuted(Context arg0, int arg1, View arg2, Object arg3, int arg4)
                        {
                            // TODO Auto-generated method stub
                        }
                    });
                }
                return holders;
            }
        })
        {
            @Override
            protected void onBeginLoad(Context arg0, Object arg1)
            {
                // TODO Auto-generated method stub
                foot.setVisibility(View.VISIBLE);
                progress.setVisibility(View.VISIBLE);
                desc.setVisibility(View.VISIBLE);
                retry.setVisibility(View.GONE);
            }

            @Override
            protected void onAfterLoad(Context arg0, Object arg1, Exception arg2)
            {
                // TODO Auto-generated method stub
                if (arg2 == null)
                {
                    foot.setVisibility(View.GONE);
                    int count = getCount();
                    if (count == 0)
                        ToastManager.showLong(arg0, R.string.generic_loading_empty);
                } else
                {
                    LogManager.logE(TroubleQueryActivity.class, "query trouble items failed.", arg2);
                    progress.setVisibility(View.GONE);
                    desc.setVisibility(View.GONE);
                    retry.setVisibility(View.VISIBLE);
                }
            }
        };
        retry.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                listAdapter.load(listAdapter.getCurCondition());
            }
        });
        list.setAdapter(listAdapter);
        query.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                if (!listAdapter.isLoading())
                {
                    listAdapter.clearDataHolders();
                    listAdapter.load(new String[] { ((SpecialtyType) type.getSelectedItem()).name, (String) area.getSelectedItem(), lon.getText().toString(), lat.getText().toString(),
                            (String) level.getSelectedItem(), getString(R.string.troublequery_list_number) });
                }
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
            {
                // TODO Auto-generated method stub
                HiddenTroubleItem item = (HiddenTroubleItem) listAdapter.queryDataHolder(arg2).getData();
                String[] params = (String[])listAdapter.getCurCondition();
                Intent intent = new Intent(TroubleQueryActivity.this, TroubleDetailActivity.class);
                intent.putExtra("TROUBLE_ITEM", item);
                intent.putExtra("LON", params[2]);
                intent.putExtra("LAT", params[3]);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (listener != null)
            mgr.removeUpdates(listener);
    }

}